package top.soulblack.purchasesale.service;

import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.soulblack.purchasesale.common.enums.OrderTypeEnum;
import top.soulblack.purchasesale.exception.PurchaseException;
import top.soulblack.purchasesale.mapper.*;
import top.soulblack.purchasesale.model.*;
import top.soulblack.purchasesale.model.DTO.GoodDTO;
import top.soulblack.purchasesale.model.DTO.OrderDTO;
import top.soulblack.purchasesale.model.VO.OrderVO;
import top.soulblack.purchasesale.model.form.OrderForm;
import top.soulblack.purchasesale.utils.KeyUtil;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 韦溜溜
 * @Description:
 * @Date: Create in 15:10 2019/7/3
 */
@Service
public class RequisitionNoteService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsSizeMapper goodsSizeMapper;

    @Autowired
    private GoodsColorMapper goodsColorMapper;

    @Autowired
    private StoreHouseService storeHouseService;

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private StoreGoodsService storeGoodsService;

    public List<GoodDTO> getGoodsOptionForOrder(){
       return goodsMapper.selectGoodsOptionForOrder();
    }

    /**
     * 获得一种商品的颜色跟尺寸属性（类似笛卡尔乘积）
     * @param barCode
     * @return
     */
    public GoodDTO getGoodCartesian(String barCode){
       List<GoodsSize> goodsSizes = goodsSizeMapper.selectGoodsSizeIdByBarCode(barCode);
       List<GoodsColor> goodsColors = goodsColorMapper.selectGoodsColorIdByBarCode(barCode);
       GoodDTO goodDTO = new GoodDTO();
       goodDTO.setBarCode(barCode);
       goodDTO.setColors(goodsColors);
       goodDTO.setSizes(goodsSizes);
       return goodDTO;
    }

    @Transactional
    public List<OrderDTO> createRequisitionNote(OrderForm orderForm) {
        String barCode = orderForm.getGoodsBarCode();
        String openid = orderForm.getOpenid();
        String goodsName = new String();
        int[] store = new int[100];
        //插入与返回的变量
        List<OrderMaster> insertOrderMasterList = new ArrayList<>();
        List<OrderDetail> insertOrderDetailList = new ArrayList<>();
        //补货商品
        OrderMaster replenishOrderMaster = new OrderMaster();
        replenishOrderMaster.setOrderId(KeyUtil.getUniqueKey());
        List<OrderDetail> replenishOrderDetailList = new ArrayList<>();
        //DTO
        List<OrderDTO> orderDTOList = new ArrayList<>();
        //生成订单
        for (OrderDetail orderDetail : orderForm.getOrderDetailList()) {
            //根据colorId和sizeId查找sku ->>>>拼接出order_detail
            Goods good = goodsService.selectSKUBycolorIdAndSizeIdAndBarCode(barCode, orderDetail.getSizeId(), orderDetail.getColorId());
            goodsName = good.getName();
            //假如good唯一的id属性。
            orderDetail.setGoodId(new BigInteger(good.getId().toString()));
            orderDetail.setGoodPrice(good.getSalePrice());
            //根据用户openid获取门店
            User user = userService.selectByOpenid(openid);
            List<StoreHouse> storeHouses  = storeHouseService.selectByShopId(user.getShopId());
            //根据sku查询仓库信息（有货除本仓库外）
            List<StoreGoods> storeGoodsList = storeGoodsService.selectByGoodId(orderDetail.getGoodId());

            //根据门店信息获取过滤掉本仓库信息。
            for (StoreHouse storeHouse : storeHouses) {
                storeGoodsList = storeGoodsList.stream()
                        .filter(storeGoods -> !(storeHouse.getStoreId().equals(storeGoods.getStoreId())
                                || storeGoods.getStock().compareTo(orderDetail.getGoodQuantity()) == -1)
                        ).collect(Collectors.toList());
            }
            //在符合条件的仓库中取出最上面的一个，一般为storeId最小的。
            //创建新的orderMaster.
            if (storeGoodsList.size() != 0) {
                //取符合条件仓库中的最上面一个
                StoreGoods canUseStore = storeGoodsList.get(0);
                if (store[canUseStore.getStoreId()] == 0) {
                    String orderId = KeyUtil.getUniqueKey();
                    OrderMaster orderMaster = new OrderMaster();
                    orderMaster.setGoodsBarCode(barCode);
                    //取操作人所属门店的的最上面一个
                    orderMaster.setInStoreId(storeHouses.get(0).getStoreId());
                    orderMaster.setOutStoreId(canUseStore.getStoreId());
                    orderMaster.setInShopId(storeHouses.get(0).getShopId());
                    /**
                     *查询调出仓库
                     */
                    StoreHouse outHouse = storeHouseService.findOneById(canUseStore.getStoreId());

                    orderMaster.setOutShopId(outHouse.getShopId());
                    orderMaster.setOpenid(openid);
                    orderMaster.setOrderId(orderId);
                    orderMaster.setGoodsName(goodsName);
                    orderMaster.setGoodsNumber(good.getGoodsNumber());
                    BigDecimal quantity = new BigDecimal(orderDetail.getGoodQuantity().toString());
                    orderMaster.setOrderAmount(orderDetail.getGoodPrice().multiply(quantity));
                    insertOrderMasterList.add(orderMaster);
                    //给orderDetail增加orderId
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.getUniqueKey());
                    insertOrderDetailList.add(orderDetail);
                    //拼接OrderDTO

                    OrderDTO orderDTO = new OrderDTO();
                    BeanUtils.copyProperties(orderMaster, orderDTO);
                    orderDTO.setOutStoreName(outHouse.getStoreName());
                    orderDTO.setInStoreName(storeHouses.get(0).getStoreName());
                    orderDTO.getOrderDetailList().add(orderDetail);
                    orderDTOList.add(orderDTO);

                    store[orderMaster.getOutStoreId()] = insertOrderMasterList.size() - 1;
                } else {
                    Integer index = store[canUseStore.getStoreId()];
                    OrderMaster orderMaster = insertOrderMasterList.get(index);
                    orderDetail.setOrderId(orderMaster.getOrderId());
                    /**
                     * 计算总价
                     */
                    BigDecimal quantity = new BigDecimal(orderDetail.getGoodQuantity().toString());
                    BigDecimal orderAmount = orderMaster.getOrderAmount();
                    orderMaster.setOrderAmount(orderAmount.add(orderDetail.getGoodPrice().multiply(quantity)));
                    OrderDTO orderDTO = orderDTOList.get(index);
                    orderDTO.getOrderDetailList().add(orderDetail);
                    orderDTOList.add(orderDTO);
                }
            }//生成补货单
            else {
                orderDetail.setOrderId(replenishOrderMaster.getOrderId());
                orderDetail.setDetailId(KeyUtil.getUniqueKey());
                replenishOrderMaster.setInShopId(storeHouses.get(0).getShopId());
                replenishOrderMaster.setInStoreId(storeHouses.get(0).getStoreId());
                insertOrderDetailList.add(orderDetail);
                replenishOrderDetailList.add(orderDetail);
                System.out.println("补货");
                replenishOrderMaster.setOpenid(openid);
                replenishOrderMaster.setGoodsName(goodsName);
                replenishOrderMaster.setGoodsBarCode(barCode);
                replenishOrderMaster.setOrderType(OrderTypeEnum.REPLENISHMENTORDER.getCode());

                orderMasterService.inserMaster(replenishOrderMaster);
                orderDetailService.inserListOrderDetail(replenishOrderDetailList);
            }
            //清空数据
        }


        return orderDTOList;
    }

    public void insertFromVO(List<OrderVO> orderVOS){
        List<OrderMaster> orderMasterList = new ArrayList<>();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        orderVOS.forEach(e->{
            orderMasterList.add(e.getOrderMaster());
            orderDetailList.add(e.getOrderDetail());
        });
        orderDetailService.inserListOrderDetail(orderDetailList);
        orderMasterService.insertListMastert(orderMasterList);
    }

    @Transactional
    public OrderDTO getOrderByOrderId(String orderId) {
        OrderDTO orderDTO = orderMasterService.selectListByOrderId(orderId);
        orderDTO.setOrderDetailList(orderDetailService.selectByOrderId(orderId));
        return orderDTO;
    }
}
